package com.gesonet.pay.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import org.dom4j.io.SAXReader;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import com.thoughtworks.xstream.XStream;


public class XmlUtil {
	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * 
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map<String, String> doXMLParse(String strxml) throws JDOMException, IOException {
		strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
		if (null == strxml || "".equals(strxml)) {
			return null;
		}

		Map<String, String> m = new HashMap<String, String>();
		InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
		try {
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(in);
			Element root = doc.getRootElement();
			List<?> list = root.getChildren();
			Iterator<?> it = list.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String k = e.getName();
				String v = "";
				List<?> children = e.getChildren();
				if (children.isEmpty()) {
					v = e.getTextNormalize();
				} else {
					v = XmlUtil.getChildrenText(children);
				}
				m.put(k, v);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭流
			in.close();
		}
		return m;
	}

	/**
	 * 获取子结点的xml
	 * 
	 * @param children
	 * @return String
	 */
	@SuppressWarnings("rawtypes")
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(XmlUtil.getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}
		return sb.toString();
	}

	public static String obj2Xml(Object obj) {
		String xml = "";
		if (obj != null) {
			StringBuffer sb = new StringBuffer("<xml>");
			Field[] fields = obj.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				try {
					String fieldName = field.getName();
					Object fieldVal = field.get(obj);
					if (fieldVal != null && !ObjectUtils.isStaticField(field)) {
						sb.append("<" + fieldName + "><![CDATA[" + fieldVal + "]]></" + fieldName + ">");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			sb.append("</xml>");
			xml = sb.toString();
		}
		return xml;
	}

	/**
	 * @Description：将请求参数转换为xml格式的string
	 * @param parameters
	 *            请求参数
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String map2Xml(SortedMap<Object, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set<?> es = parameters.entrySet();
		Iterator<?> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + v + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}

	/**
	 * @Title: parseXml 
	 * @Description: 解析xml数据为Map方式存储
	 * @param: xml
	 * @return: Map<String,String> 
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> parseXml(String xml) throws Exception {
		// 解析结果存储在HashMap
		Map<String, String> map = new HashMap<String, String>();
		InputStream inputStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
		// 读取输入流
		SAXReader reader = new SAXReader();
		org.dom4j.Document document = reader.read(inputStream);
		// 得到xml根元素
		org.dom4j.Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<org.dom4j.Element> elementList = root.elements();

		// 遍历所有子节点
		for (org.dom4j.Element e : elementList) {
			map.put(e.getName(), e.getText());
		}
		// 释放资源
		inputStream.close();
		inputStream = null;

		return map;
	}
	
	/**
	 * 通过XStream将对象转换为xml
	 * @param obj
	 * @return xml
	 * @throws Exception
	 */
	public static String object2Xml(Object obj) throws Exception {
		XStream stream = new XStream();
		stream.autodetectAnnotations(true);
		return stream.toXML(obj);
	}
	
	/**
	 * 通过XStream将xml转换为对象
	 * @param xml xml字符串
	 * @param clazz 对象的类型
	 * @return 对象
	 * @throws Exception
	 */
	public static Object xml2Object(String xml,Class<?> clazz) throws Exception {
		XStream stream = new XStream();
		stream.processAnnotations(clazz);
		stream.autodetectAnnotations(true);
		return stream.fromXML(xml);
	}
	

	
	
}
